package com.celesea.configuration.security;

import com.celesea.framework.authority.AuthorityPrincipal;
import com.celesea.framework.jwt.JwtRedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CasRedisProvider {

    private static Logger logger = LoggerFactory.getLogger(CasRedisProvider.class);

    @Qualifier("ssoRedisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    public AuthorityPrincipal getUserInfoFromRedis(String loginSessionId) {
        logger.info("======================================>>");
        logger.info("开始从Redis获取用户信息：loginSessionId：{}", loginSessionId);
        String redisUserKey = JwtRedisUtil.getInfoKey(loginSessionId);
        Object loginInfo = readRedis(redisUserKey);
        if (loginInfo == null) {
            return null;
        }
        AuthorityPrincipal principal = (AuthorityPrincipal) loginInfo;
        principal.setUpdateTime(getUserUpdateTime(loginSessionId));
        logger.info("----->>>>>>:{}", principal.getAuthorities());

        return principal;
    }

    public Long getUserUpdateTime(String loginSessionId) {
        String updateTimeKey = JwtRedisUtil.getTimeKey(loginSessionId);
        Long updateTime = (Long) readRedis(updateTimeKey);
        return updateTime;
    }

    private Object readRedis(String token) {
        ValueOperations<String, String> redisOperation = this.redisTemplate.opsForValue();
        return redisOperation.get(token);
    }

    /**
     * 更新有效期
     *
     * @param loginSessionId
     * @param maxAge
     * @param timeUnit
     */
    public void updateExpire(String loginSessionId, Integer maxAge, TimeUnit timeUnit) {
        String redisKey = JwtRedisUtil.getInfoKey(loginSessionId);
        redisTemplate.expire(redisKey, maxAge, timeUnit);
    }

}
